package com.nakamachizu.controller.mixi;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;
import org.slim3.util.TimeZoneLocator;

import com.nakamachizu.collection.ApiKeyMap;
import com.nakamachizu.collection.IconNameMap;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.constant.SessionKeyConstant;
import com.nakamachizu.model.LandMarkData;
import com.nakamachizu.model.MapData;
import com.nakamachizu.model.MemberData;
import com.nakamachizu.model.session.MapDataSession;
import com.nakamachizu.model.session.MixiSessionData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.service.mixi.RestfulService;
import com.nakamachizu.util.ErrorsUtil;

public class MapController extends Controller {

    private String sid;
    private String pass;
    private MapDataSession mdses;
    
    private static final Logger log = Logger.getLogger(MapController.class.getName());
    protected List<String> messages = new ArrayList<String>();
    private String zoomLevel;
    private String centerLat;
    private String centerLng;
    private Calendar now;
    
    @Override
    public Navigation run() throws Exception {
        MapDataService mds = new MapDataService();
        MapData map = null;
        
        if(!validate()){
            return forward("/jsp/pc/mixi/error.jsp");
        }
        
        init();
        MixiSessionData session = mds.getMixiSessionData(sid);
        
        map = mds.getMapDataMixiViewer(session);
        
        if(map == null){
            return forward("/jsp/pc/mixi/nomap.jsp");
        }
        
        if(AppConstant.ACCESSLEVEL_FRIENDS().equals(map.getAccessLevel())){
            RestfulService rfs = new RestfulService();
            if(!rfs.isFriend(session)){
                return forward("/jsp/pc/mixi/nomap.jsp");
            }
        }
        
        if(!StringUtil.isEmpty(map.getViewPassword())){
            if(StringUtil.isEmpty(pass) && session != null){
                pass = session.getViewPassword();
            }
            if(!map.getViewPassword().equals(pass)){
                if(!StringUtil.isEmpty(pass)){
                    messages.add("パスワードが違います。");
                    requestScope("messages", messages);
                }
                return forward("/jsp/pc/mixi/input_password.jsp");
            }
        }
        
        init();
        
        Integer w = 600;
        Integer h = 370;
        
        List<MemberData> memList = map.getMemberDataListRef().getModelList();
        List<LandMarkData> landList = map.getLandMarkDataListRef().getModelList();

        if(StringUtil.isEmpty(centerLat) || StringUtil.isEmpty(centerLng)){
            if(landList != null && landList.size() > 0){
                centerLat = Float.toString(landList.get(0).getLatLng().getLatitude());
                centerLng = Float.toString(landList.get(0).getLatLng().getLongitude());
            }else if(memList != null && memList.size() > 0){
                centerLat = Float.toString(memList.get(0).getLatLng().getLatitude());
                centerLng = Float.toString(memList.get(0).getLatLng().getLongitude());
            }else{
                centerLat = "35.6810976";
                centerLng = "139.7671169";
            }
        }
        requestScope("landMarkList", landList);
        requestScope("memberList", memList);
        
        requestScope("cLat", centerLat);
        requestScope("cLng", centerLng);
        requestScope("zoom", zoomLevel);
        requestScope("messages", messages);
        requestScope("now", now.getTime().getTime());
        requestScope("serverName", request.getServerName());
        requestScope("apiKey", ApiKeyMap.API_KEY_MAP.get(request.getServerName()));
        requestScope("width", w);
        requestScope("height", h);
        requestScope("iconNameMap", IconNameMap.ICON_NAME);
        requestScope("expire", map.getExpire());
        requestScope("mapKey", map.getAccessKey());
        requestScope("accessLevel", map.getAccessLevel());
        requestScope("viewPassword", map.getViewPassword());
        requestScope("title", map.getTitle());
        //sessionScope(SessionKeyConstant.MAP_DATA_SESSION_KEY(), mds.createMapDataSession(map));
        
        session.setViewPassword(pass);
        Datastore.put(session);
        requestScope("sid", sid);
        return forward("/jsp/pc/mixi/map.jsp");
    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("sid", v.required());
        result = v.validate();
        
        return result;
    }
    
    protected void init(){

        mdses = sessionScope(SessionKeyConstant.MAP_DATA_SESSION_KEY());
        sid = requestScope("sid");
        pass = requestScope("viewPassword");
        now = Calendar.getInstance(TimeZoneLocator.get());
        zoomLevel = requestScope("zoom");
        if(StringUtil.isEmpty(zoomLevel)){
            zoomLevel = AppConstant.DEFAULT_ZOOM_LEVEL();
        }


    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("/jsp/pc/mixi/error.jsp");
    }
}
